import { Investment, YieldCalculation, RateRecord } from '../types/product';

// 计算两个日期之间的天数
export const getDaysBetween = (start: Date, end: Date): number => {
  const oneDay = 24 * 60 * 60 * 1000;
  return Math.round(Math.abs((end.getTime() - start.getTime()) / oneDay));
};

// 检查时间冲突
export const checkTimeConflicts = (
  startDate: Date,
  endDate: Date,
  existingPeriods: { startDate: Date; endDate: Date }[]
): boolean => {
  return existingPeriods.some(period => {
    const periodStart = new Date(period.startDate);
    const periodEnd = new Date(period.endDate);
    
    // 检查是否有重叠
    return (
      (startDate >= periodStart && startDate <= periodEnd) ||
      (endDate >= periodStart && endDate <= periodEnd) ||
      (startDate <= periodStart && endDate >= periodEnd)
    );
  });
};

// 计算加权收益
export const calculateWeightedYield = (
  investments: Investment[],
  totalProfit: number
): YieldCalculation => {
  let totalAmount = 0;
  let weightedDays = 0;
  const now = new Date();
  
  investments.forEach(inv => {
    const endDate = inv.redeemDate || now;
    const days = getDaysBetween(new Date(inv.purchaseDate), endDate);
    totalAmount += inv.amount;
    weightedDays += inv.amount * days;
  });

  const averageWeightedDays = weightedDays / totalAmount;
  const dailyRate = (totalProfit / totalAmount) / averageWeightedDays;
  const annualizedRate = dailyRate * 365 * 100; // 转换为百分比
  const dailyProfitPerTenThousand = dailyRate * 10000;

  return {
    totalAmount,
    totalProfit,
    annualizedRate,
    averageNetWorth: 1 + (totalProfit / totalAmount),
    startDate: new Date(Math.min(...investments.map(inv => inv.purchaseDate.getTime()))),
    endDate: now,
    daysCount: averageWeightedDays,
    dailyRate,
    dailyProfitPerTenThousand
  };
};

// 分析收益波动
export const analyzeProfitVolatility = (
  dailyProfits: number[]
): { isVolatile: boolean; deviation: number } => {
  if (dailyProfits.length === 0) {
    return { isVolatile: false, deviation: 0 };
  }

  const average = dailyProfits.reduce((a, b) => a + b) / dailyProfits.length;
  const deviation = Math.sqrt(
    dailyProfits.reduce((sum, profit) => sum + Math.pow(profit - average, 2), 0) / dailyProfits.length
  ) / average;

  return {
    isVolatile: deviation > 0.3, // 波动超过30%认为是波动较大
    deviation
  };
};

// 分析收益率记录
export const analyzeRateRecords = (records: RateRecord[]): {
  averageRate: number;
  maxRate: number;
  minRate: number;
  volatility: number;
} => {
  if (records.length === 0) {
    return {
      averageRate: 0,
      maxRate: 0,
      minRate: 0,
      volatility: 0
    };
  }

  const rates = records.map(r => r.rate);
  const averageRate = rates.reduce((a, b) => a + b, 0) / rates.length;
  const maxRate = Math.max(...rates);
  const minRate = Math.min(...rates);
  const volatility = Math.sqrt(
    rates.reduce((sum, rate) => sum + Math.pow(rate - averageRate, 2), 0) / rates.length
  );

  return {
    averageRate,
    maxRate,
    minRate,
    volatility
  };
};